<template>
    <div class="intelligent-test-pape-node">
        <div class="selection-section">
            <h3 v-if="intelligentObj.shape  == 1">选择章节</h3>
            <h3 v-if="intelligentObj.shape == 2">选择知识点</h3>
            <div class="selection-section-tree">
                <el-scrollbar>

                <el-input class="filterText" v-show="chapterList.length > 0"
                          placeholder="输入关键字进行过滤" clearable
                          v-model="filterText"></el-input>
                 <el-tree class="question-tree"
                     :data="chapterList"
                     show-checkbox
                     node-key="id" ref="tree"
                     default-expand-all
                     :filter-node-method="filterNode"
                     highlight-current
                     :props="defaultProps"
                     @check="handleCheckChange">
                 </el-tree>

                </el-scrollbar>
            </div>
        </div>
        <div class="selection-content">
        	<div class="chapter-num">
        		<div class="chapter-title">
        			<span v-if="intelligentObj.shape  == 1">已选择章节（{{chapterCheck.length ? chapterCheck.length : 0}}个）</span>
                    <span v-if="intelligentObj.shape  == 2">已选择知识点（{{chapterCheck.length ? chapterCheck.length : 0}}个）</span>
        			<span @click="deleteChapter()"><i class="el-icon-delete" ></i>清空</span>
        		</div>
        		<div class="chapter-list">
        			<el-tag
        			  :key="index" closable
        			  v-for="(item, index) in chapterCheck"
        			  :disable-transitions="false"
        			  @close="handleClose(index, item.id)">
        			  {{item.name}}
        			</el-tag>
        		</div>
        	</div>

        	<div class="question-type">
        		<div class="chapter-title">
        			<span>题型/题量设置</span>
        		</div>

        		<div class="question-type-num">
        			
        			<div class="question-type-list" >
        				<el-checkbox-group v-model="questionType">
                            <template v-for="item of questionList">
                               <el-checkbox  :label="item.id" disabled>{{item.name}}</el-checkbox>
                           </template>
        				</el-checkbox-group>
        			</div>

        			<ul class="" v-loading="loading">
                        <template v-for="(item, index) of questionList">

            				 <li class="question-node" :key="index">
            				 	<span>{{item.name}}:</span>
            				 	<div class="question-node-cont">
                                    <template v-for="(difficulity, index2) of item.difficulity">
                                        <span>
                                            <strong>{{difficulity.name}}</strong>
                                            <el-input-number @change="changeSelect(index,item.item, difficulity.question_select)" v-model="difficulity.question_select" controls-position="right" :step="1" step-strictly :min="0" :max="difficulity.question"></el-input-number>
                                            <i>{{difficulity.question ? difficulity.question : 0}}道试题可用</i>
                                        </span>
                                    </template>
            				 	</div>
                                <el-tooltip class="item" effect="dark" content="重置试题可用数量" placement="top-start">
                                   <i class="el-icon-refresh" @click="setQuestion(index, item.id)"></i>
                               </el-tooltip>
            				 	
            				 </li>
                        </template>
        			</ul>

        			<div class="question-type-butn" v-show="questionList.length > 0">
        				 <el-button type="primary" @click="submitPapers()" v-preventReClick>生成试卷</el-button>
        			</div>
        		</div>

                <div class="dependent" v-if="questionList.length > 0 ? placeholder = false : placeholder = true">
                    <i class="ipng image_state01"></i>
                    <p>还没发现任何相关的内容哦~</p>
                </div>
        	</div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            // materiaid: this.$route.query.material, /*教材id*/
            // shapeTyle: this.$route.query.type,       /*组卷形式 1章节 2知识点*/
            chapterList: [],    /* 章节列表*/
            knowledgeList: [],  /*知识点*/
            filterText: '',     /*章节的关键词*/
            filterText2: '',    /*知识点的关键词*/
            chapterID: [],      /*章节 & 知识点 选中的id*/
            knowledgeID: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            chapterCheck: [],       /*已选择章节*/
            questionType: [],       /*题型/题量设置*/
            checkArray: [],
            testList: [],           /*试卷列表*/
            getTestTypeList: [],    /*题型列表*/
            intelligentObj: JSON.parse(sessionStorage.getItem('intelligentObj')), /*智能组卷携带是信息*/
            number: '',
            questionList: [],       /*题型/题量设置数组*/
            questionCate: [],       /*选择的题型*/
            loading: false,
            total: '',
            placeholder: false,
            checkList: [],

        };
    },
    created(){

    },
    mounted(){
        this.getChapter()
        // this.$nextTick(()=>{ this.getChapter() })
    },
    destroyed(){
        /**
         * 离开当前页面时，移除之前的自定义class类名
         */
        // this.headClassList.remove('hidden-header')
    },
    watch: {
        /*章节的关键词*/
        filterText(val) {
            this.$refs.tree.filter(val);
        },
        /*知识点的关键词*/
        filterText2(val) {
            this.$refs.tree2.filter(val);
        }
    },
    methods: {
 
        /**
         * 章节 || 知识点所对应的对象、树目前的选中状态对象
         * @DateTime 2019-07-24T09:37:48+0800
         * @param    {[Strong]}   data    选中的章节 || 知识点的节点对象
         * @param    {[Array]}    checked 选中的章节 || 知识点包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性来读取选中的id,对象结构
         */
        handleCheckChange(data, checked) {
            /*选中的id*/
            this.checkList =  checked.checkedKeys
            // console.log(checked.checkedKeys);
            this.loading = true;
            this.chapterCheck = [];
            let checkedArr = [];
            if (this.intelligentObj.shape == '1') {
                // console.log(1);
                // this.chapterID = [...checked.halfCheckedKeys, ...checked.checkedKeys];
                checkedArr = [...checked.halfCheckedKeys, ...checked.checkedKeys];
            }else{
                // console.log(2);
                // this.knowledgeID = [...checked.halfCheckedKeys, ...checked.checkedKeys];
                checkedArr = [...checked.halfCheckedKeys, ...checked.checkedKeys];
            }

            this.chapterID = checkedArr
            
            this.setCheckNade()
            this.getTestList();
            this.getQuestionList()

           
        },
        /**
         * 已选择章节
         * @DateTime 2019-07-25T18:03:00+0800
         */
        setCheckNade(){

            for (let i = 0; i < this.chapterList.length; i++) {

                if (this.chapterID.includes(this.chapterList[i].id) && this.chapterList[i].children.length > 0) {

                   for (let j = 0; j < this.chapterList[i].children.length; j++) {
                       
                       if (this.chapterID.includes(this.chapterList[i].children[j].id)) {
                            this.chapterCheck.push({
                                id: this.chapterList[i].children[j].id,
                                name: `${this.chapterList[i].name} > ${this.chapterList[i].children[j].name}`
                            })
                       }
                   }
                }else if (this.chapterID.includes(this.chapterList[i].id) && this.chapterList[i].children.length=== 0) {
                    this.chapterCheck.push({
                        id: this.chapterList[i].id,
                        name: `${this.chapterList[i].name}`
                    })
                }
            }
        },
        /**
         * 关键词过滤，搜索想要的条件
         * @DateTime 2019-07-23T16:36:20+0800
         * @param    {Strong}  value 是输入发关键字
         * @param    [type]    data  是搜索的条件数组
         */
        filterNode(value, data) {
            if (!value) return true;
            //根据关键字匹配数据是否存在，存在就返回对应的条件数据
            return data.name.indexOf(value) !== -1;
        },
        /**
         * 请求章节数据
         * @DateTime 2019-07-23T14:04:49+0800
         * @return   {[type]}                 [description]
         */
        getChapter(){

            let success = (res=>{
                this.chapterList = res.data;

                /*重新配置智慧组卷的数据*/
                if (this.$route.query.edit) {
                    let check = sessionStorage.getItem('check')/*选中的章节 & 知识点*/
                    let check2 = sessionStorage.getItem('check2')/*选中的id*/
                    let check3 = sessionStorage.getItem('check3')
                    check = check.split(',').map(item => parseInt(item))
                    check2 = check2.split(',').map(item => parseInt(item))
                    this.chapterID = check2
                    this.$refs.tree.setCheckedKeys(check, true)
                    this.setCheckNade()
                    this.getQuestionList()
                }

            });
            let params = {
                material_id: this.intelligentObj.material,
                type: this.intelligentObj.shape == '1' ? 1 : 2
            };
            let fail = (res=>{
                this.$message.error({
                    duration: 8000,
                    message: res.msg
                })
            })

            this.$ajax({
                url: 'api/newtest/get_list_know_by_material',
                method: 'get',
                params: params,
                func: {success: success, fail: fail}
            })
        },
        /**
         * 删除已选择章节
         * @DateTime 2019-07-26T13:37:51+0800
         * @param    {[strong]}   index 选择章节的索引
         * @param    {[strong]}   id    选择章节的id
         */
        handleClose(index, id) {
            this.loading = true;

            /*删除已选择章节的数据*/
        	this.chapterCheck.splice(index, 1);
            /*根据 id 查找索引删除对应的 id*/
            this.chapterID.splice(this.chapterID.indexOf(id), 1)
            /*根据删除的的节点id,取消章节树对象的勾选*/
            this.$refs.tree.setChecked(id, false)
            if (this.chapterID.length === 1) {
                this.chapterID = []
            }
            this.getQuestionList()

        },
        /**
         * 是否清空已选择章节？
         */
        deleteChapter(){
            this.$confirm('是否清空已选择章节？', '提示', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                type: 'warning',
                customClass: "test-message"
            }).then(() => {
                this.$message.success('删除成功!');

                this.chapterCheck= [];
                this.chapterID = []
                this.$refs.tree.setCheckedKeys([])
                this.getQuestionList()
            }).catch(() => {});
        },
        /**
         * 请求试题列表
         * @DateTime 2019-07-22T13:47:02+0800
         */
        getTestList(){
            let success = ( res=>{
                this.testList = res.data.data;
            });

            let params = {
                user_id: this.$g.user_id,
                page_index: 1,
                page_size: 0,
                grade_id: this.intelligentObj.grade,
                subject_id: this.intelligentObj.subject,
                version_id: this.intelligentObj.edition,
                // type_id: this.question.type,
                list_id: this.chapterID,
                know_id:  this.chapterID,
                type: 'default',
            };

            this.$ajax({
                url: 'api/newtest/test_question_list',
                method: 'get',
                params: params,
                func: {success: success}
            })
        },
        /**
         * 根据章节id/知识点id 获取题目数量
         * @DateTime 2019-07-31T10:35:56+0800
         * @return   {[type]}                 [description]
         */
        getQuestionList(){
            
            [this.questionCate, this.questionList] = [[], []];
            let success = (res=>{

                let questionList = res.data;
                for (let type in res.data.question_type ) {
                    this.questionList.push({    /*组装题目的数组*/
                        type: type,  
                        bol: false,                                                   /*题型*/
                        id: questionList.question_type[type].id,                   /*题目id*/
                        name:  questionList.question_type[type].name,              /*题目名称*/
                        difficulity: questionList.question_type[type].difficulity  /*题目难度*/
                    })
                }
                this.loading = false
            });

            let params = {
                cate_id: this.chapterID,
                type: this.intelligentObj.shape
            };

            let fail = (res=>{
                this.loading = false;
                this.$message.error(res.msg)
            })
            this.$ajax({
                url: 'api/newtest/get_question_num_by_cate_list',
                method: 'get',
                params: params,
                func: { success: success, fail: fail}
            })
        },
        /**
         * 重置试题的数量
         * @DateTime 2019-07-31T14:33:34+0800
         * @param    {[strong]}    index 根据索引index重置数组的对象
         */
        setQuestion(index){
            
            if (this.questionList[index].difficulity.length ===  0) {return}
            for (let i = 0; i < this.questionList[index].difficulity.length; i++) {
                this.questionList[index].difficulity[i].question_select = 0
            }
            /*重置后删除题型高亮*/
            this.questionType.splice( this.questionType.indexOf(this.questionList[index].id),1)
        },
        /**
         * 改变题量试题可用数
         * @DateTime 2019-08-01T17:36:48+0800
         * @return   {[type]}                 [description]
         */
        changeSelect(index , id, val){

            let [sun, array] = [0, []];
            sun += parseInt(val)
           if (sun >= 1) {
                // 如果数组不存在新值就pussh数组里，否则不进行操作
                !this.questionType.includes(this.questionList[index].id) && this.questionType.push(this.questionList[index].id)
           }else{
                //sun为 0 时，删除对应的参数改变题型高亮的状态
                this.questionType.splice( this.questionType.indexOf(this.questionList[index].id),1)
           }
        },
        /**
         * 遍历题量设置组装返回后台的数组对象
         * @DateTime 2019-08-02T11:37:47+0800
         */
        setQuestionNumber(){

            this.total = [];
            for (let i = 0; i < this.questionList.length; i++) {

                for (let j = 0; j < this.questionList[i].difficulity.length; j++) {
                    if (this.questionList[i].difficulity[j].question_select > 0) {
                        this.total.push({
                            'question_type': this.questionList[i].id,
                            'difficulity_id': this.questionList[i].difficulity[j].id,
                            'question_num': this.questionList[i].difficulity[j].question_select,
                        })
                    } 
                }
            }
        },
        /**
         * 生成试卷
         * @DateTime 2019-08-01T17:42:59+0800
         * @return   {[type]}                 [description]
         */
        submitPapers(){
            if (this.questionType.length === 0) { 
                 return  this.$message.warning('试题数量不能为0， 请填写试题数量');
            }

            // if (this.$route.query.edit) {

            // }
            // this.tota = []
            // this.questionList = []
            this.setQuestionNumber();

            let success = (res =>{
                this.$message.success(res.msg);
                this.$router.push({path: '/test/preview-test', query: {id: this.$route.query.id}})
                sessionStorage.setItem('check',  this.checkList)
                sessionStorage.setItem('check2',  this.chapterID)
                // sessionStorage.setItem('check3',  JSON.stringify(this.questionList))
                this.tota = []

            });

            let params = {
                type:  this.intelligentObj.shape,
                test_id: this.$route.query.id,
                cate_id:  this.chapterID,
                question_list:  this.total,
                authority: 0,
                status: 0,
            };
            this.$ajax.post('api/newtest/add_test_intell', params, {func: {success: success}})
        }

    }
};
</script>